/* 
 * Events Helpers
 */

Ext.namespace('myApp.helpers.Events');

myApp.helpers.Events = {

    updateTimeElapsed : function(controller,action,flagSaveData){
        if(typeof controller != 'string' && typeof action != 'string'){
            controller = arguments[2].controller;
            action = arguments[2].action;
            flagSaveData = arguments[2].flagSaveData;
        }
        if(typeof flagSaveData != 'boolean')
            flagSaveData = false;

        //console.log('--> Events.updateTimeElapsed',controller,action,flagSaveData);
        myApp.stores.IndexLinks.updateTimeElapsed(controller,action,flagSaveData);
    },
    initUnloadListener : function(controller,action){
//        var eventCallback = myApp.helpers.Events.updateTimeElapsed;
        var eventCallback = eventCallback || {};//if no eventCallback var, we create it
        eventCallback[controller+action] = myApp.helpers.Events.updateTimeElapsed;
        Ext.EventManager.removeListener(window, 'unload', eventCallback[controller+action]);
        Ext.EventManager.addListener(window, 'unload', eventCallback[controller+action], this, {'controller':controller,'action':action,flagSaveData:true});
    },
    addTimerListenersToView : function(panel,controller,action){

        //code needed because of closure inside timer callback
        //otherwise, the callback will point on the wrong controller/action
        this.timerConfig = this.timerConfig || {};
        this.timerConfig.lastActiveController = this.timerConfig.activeController || controller;
        this.timerConfig.lastActiveAction = this.timerConfig.activeAction || action;
        this.timerConfig.activeController = controller;
        this.timerConfig.activeAction = action;

        //console.info('addTimerListenersToView',controller,action);
        panel.addListener('activate',function(){
            myApp.helpers.timer.start(function(){
                //console.info('activate',myApp.helpers.Events.timerConfig.activeController,myApp.helpers.Events.timerConfig.activeAction);
                this.setTimeElapsed(myApp.stores.IndexLinks.getTimeElapsed(myApp.helpers.Events.timerConfig.activeController,myApp.helpers.Events.timerConfig.activeAction));
            });
        });
        panel.addListener('beforedeactivate',function(){
            myApp.helpers.timer.stop(function(){
                //console.info('beforedeactivate',myApp.helpers.Events.timerConfig.lastActiveController,myApp.helpers.Events.timerConfig.lastActiveAction);
                //console.log('timeElapsed : '+this.getTimeElapsed()+' formatted : '+TophemanUtils.formatTime(this.getTimeElapsed()));
                myApp.helpers.Events.updateTimeElapsed(myApp.helpers.Events.timerConfig.lastActiveController,myApp.helpers.Events.timerConfig.lastActiveAction,false);
            });
        })
        this.initUnloadListener(controller,action);
    }
    
}